﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using LDSP.BRL;
using BYFW.BOL;
using LDSP.Util;
using System.Drawing;
using BLL.Util;
using LDSP.Helper;

namespace LDSP.UI.Admin
{
    public partial class BatchAddFavorite : LDSP.BRL.BaseEnterpriseAdminPage
    {
        private static readonly string COL_NAME = "name";
        private static readonly string COL_IS_ADDED = "isAdded";
        private static readonly string COL_TYPE = "type";
        private static readonly string COL_NAME_IN_PLATFORM = "name_platform";
        private static readonly string COL_IS_EXACTLY_MATCH = "isExactlyMatch";

        private static readonly int idx_NAME = 2;
        private static readonly int idx_IS_ADDED = 3;
        private static readonly int idx_TYPE = 4;
        private static readonly int idx_NAME_IN_PLATFORM = 5;
        private static readonly int idx_IS_EXACTLY_MATCH = 6;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.RB())
                {
                    this.InitDataDynamicBefore();
                    if (!IsPostBack)
                    {
                        this.InitDataSelect();
                    }
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        private void InitDataDynamicBefore()
        {
            //隐藏checkbox的显示。
            this.grd_list.Columns[0].Visible = false;
        }

        protected bool RB()
        {
            return this.AllowEnterpriseUser();
        }

        protected void InitDataSelect()
        {
            DataTable dt = GetDatatable();
            dt.Rows.Add("", false, null, null, false);
            this.grd_list.DataSource = dt;

            this.grd_list.DataBind();
        }

        protected void ValidateDataBefore()
        {
        }

        protected void ValidateDataAfter()
        {
        }

        protected void SetData()
        {
            this.ValidateDataBefore();
            this.ValidateDataAfter();
        }

        private void BindGrid()
        {
            BRL.Codification ett = new BRL.Codification();
            DataTable dt = ett.GetRecordsByEnterpriseID(0);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                BRL.Codification tmp = new BRL.Codification();
                tmp.GetProperties(dt.Rows[i]);
                try
                {
                    if (tmp.FileName != "" && File.Exists(tmp.GetDownloadFileFullName()))
                    {
                        dt.Rows.RemoveAt(i);
                        i--;
                    }
                }
                catch { }
            }
            this.grd_list.DataSource = dt;
            this.grd_list.DataBind();
        }

        protected void btn_check_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.fuldCodification.HasFile == true)
                {
                    string tmpFile = SaveToFile(this.fuldCodification);
                    IList<CodificationSummary> codToCheckList = GetCodList(tmpFile);
                    DataTable checkResult = Check(codToCheckList);

                    this.grd_list.DataSource = checkResult;
                    this.grd_list.DataBind();

                    ClearTmpFile(tmpFile);
                }
                else
                {
                    this.JSAlert("请输入文件路径!");
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        private void ClearTmpFile(string tmpFile)
        {
            string fileName = Server.MapPath(tmpFile);
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }
        }

        private DataTable Check(IList<CodificationSummary> codToCheckList)
        {
            DataTable result = GetDatatable();

            if (codToCheckList != null && codToCheckList.Count > 0)
            {
                foreach (CodificationSummary sum in codToCheckList)
                {
                    IList<Codification> cods = new Codification().GetCodificationByName(sum.CodName);
                    IDictionary<string, Codification> validCods = new Dictionary<string, Codification>();
                    Codification matchedCode = null;

                    //不存在
                    DataRow row = result.Rows.Add(sum.CodName, false, null, null, false);

                    if (cods != null && cods.Count > 0)
                    {
                        //检查是否有权限查看
                        foreach (Codification cod in cods)
                        {
                            if (HaveCatalogPermission(cod.CatalogID))
                            {
                                validCods.Add(cod.Name, cod);
                            }
                        }

                        if (validCods.Count == 0)
                        {//不存在,因为所有存在的都没有权限查看
                            row[COL_NAME] = sum.CodName;
                            row[COL_IS_ADDED] = false;
                            row[COL_NAME_IN_PLATFORM] = sum.CodName;
                            row[COL_IS_EXACTLY_MATCH] = false;
                            row[COL_TYPE] = "不存在";
                        }
                        else if (validCods.Count > 0 && validCods.ContainsKey(sum.CodName))
                        {
                            //成功且精确匹配
                            row[COL_NAME] = sum.CodName;
                            row[COL_IS_ADDED] = true;
                            row[COL_NAME_IN_PLATFORM] = sum.CodName;
                            row[COL_TYPE] = validCods[sum.CodName].DocType.ToString();
                            row[COL_IS_EXACTLY_MATCH] = true;

                            matchedCode = validCods[sum.CodName];
                        }
                        else if (validCods.Count == 1)
                        {//成功但模糊匹配
                            row[COL_NAME] = sum.CodName;
                            row[COL_IS_ADDED] = true;
                            row[COL_NAME_IN_PLATFORM] = validCods.Keys.First<string>();
                            row[COL_TYPE] = validCods.Values.First<Codification>().DocType.ToString();
                            row[COL_IS_EXACTLY_MATCH] = false;

                            matchedCode = validCods.Values.First<Codification>();
                        }
                        else if (validCods.Count > 1)
                        {
                            //存在过多的且无精确匹配项
                            row[COL_NAME] = sum.CodName;
                            row[COL_IS_ADDED] = false;
                            row[COL_TYPE] = "过多匹配项";
                        }
                    }
                    else
                    {
                        row[COL_NAME] = sum.CodName;
                        row[COL_IS_ADDED] = false;
                        row[COL_TYPE] = "不存在";
                    }

                    if (bool.Parse(row[COL_IS_ADDED].ToString()) == true)
                    {
                        AddFavirote(true, matchedCode, this.LoginUser.Enterprise);
                    }
                }
            }
            else
            {
                result.Rows.Add(string.Empty, false, null, null, false);
            }

            return result;
        }

        private static DataTable GetDatatable()
        {
            DataTable result = new DataTable();
            result.Columns.Add(COL_NAME);
            result.Columns.Add(COL_IS_ADDED);
            result.Columns.Add(COL_TYPE);
            result.Columns.Add(COL_NAME_IN_PLATFORM);
            result.Columns.Add(COL_IS_EXACTLY_MATCH);
            return result;
        }

        private IList<CodificationSummary> GetCodList(string tmpFile)
        {
            IList<CodificationSummary> summaryList = new List<CodificationSummary>();
            ExcelClass excel = new ExcelClass(Server.MapPath(tmpFile));
            DataTable dt = excel.ToDataTable();

            //将显示顺序倒置以便按最开始Excel里的顺序显示结果，因为读取Excel时倒置了。
            for (int i = dt.Rows.Count - 1; i >= 0; i--)
            {
                CodificationSummary sum = new CodificationSummary();
                sum.CodName = dt.Rows[i][0] != DBNull.Value ? dt.Rows[i][0].ToString() : string.Empty;

                if (!string.IsNullOrEmpty(sum.CodName))
                {
                    summaryList.Add(sum);
                }
            }

            return summaryList;
        }

        private string SaveToFile(FileUpload fileUpload)
        {
            //File Name: ImpImg + [Login Enterprise ID] + [Current Date] + [Random number].
            string fileName = this.LoginUser.EnterpriseID + "_" + DateTime.Now.ToString("yyMMdd") + "_" + new Random().Next().ToString() + ".xls";

            fileUpload.PostedFile.SaveAs(Server.MapPath(@"~\TmpImg\") + fileName);

            return @"~\TmpImg\" + fileName;
        }

        protected void grd_list_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    CodificationAddFavoriteResult ett = new CodificationAddFavoriteResult();
                    ett.GetProperties(((DataRowView)e.Row.DataItem).Row);

                    if (!string.IsNullOrEmpty(ett.CodName))
                    {
                        this.ShowSequenceNumber(e.Row, 1);

                        //是否成功
                        e.Row.Cells[idx_IS_ADDED].Text = ett.IsAdded == true ? "是" : "否";

                        //是否精确匹配
                        string isExactlyMatch = string.Empty;
                        if (ett.IsAdded == true)
                        {
                            isExactlyMatch = ett.IsExactlyMatch == true ? "是" : "否";
                        }
                        e.Row.Cells[idx_IS_EXACTLY_MATCH].Text = isExactlyMatch;

                        //更新颜色，
                        //失败            --------    淡红色
                        //成功但模糊匹配   --------    淡黄色
                        //成功且精确匹配   --------    淡绿色
                        if (ett.IsAdded == false)
                        {
                            e.Row.BackColor = Color.MistyRose;
                        }
                        else if (ett.IsExactlyMatch == false)
                        {
                            e.Row.BackColor = Color.LightYellow;
                        }
                        else
                        {
                            e.Row.BackColor = Color.PaleGreen;
                        }
                    }
                    else
                    {
                        e.Row.Cells[idx_IS_ADDED].Text = string.Empty;
                        e.Row.Cells[idx_IS_EXACTLY_MATCH].Text = string.Empty;
                    }
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        protected void btnDownloadTemplate_Click(object sender, EventArgs e)
        {
            DownloadFile("~/Templates/BatchAddFavorite.xls");
        }

        protected void btn_SendMail_Click(object sender, EventArgs e)
        {
            IList<string> bcc = new List<string>() { "pablo.tao@dowann.com" };
            string subject = "[LDSP][" + this.LoginUser.Enterprise.Code + "][" + this.LoginUser.Code + "]批量导入适用法规/标准的结果。";
            string content = UIHelper.ConvertGridViewToHtml(this.grd_list);

            MailSender.SendMail(bcc, subject, content, null, null);
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            return;
        }
    }
}